package com.rhythm.commons.io;

import java.io.File;
import static com.rhythm.base.Preconditions.assertNotNull;

/**
 *
 * @author mlee
 */
public class Directory {

    /**
     * Returns if the given {@code path} is a valid directory folder.  Returns
     * {@code false} if the given path is null.
     *
     * @param path nullable
     * @return {@code true} if the given {@code path} is a valid directory folder.   {@code false} otherwise.
     */
    public static synchronized boolean exists(String path) {
        return ((path == null) ? false : new File(path).isDirectory());
    }

    /**
     * Creates a directory folder for the given path.  Returns {@code false} if the given path is null.
     * @param path nullable
     * @return {@code true} if the director was created. {@code false} otherwise.
     */
    public static synchronized boolean create(String path) {
        return ((path == null) ? false : new File(path).mkdir());
    }

    /**
     * Recursivly delets a directory and all its files.  Returns {@code true} if successful.  Returns
     * {@code false} if path is null or does not exist.
     *
     * @param path
     * @return
     */
    public static synchronized boolean delete(String path) {

        if (path == null) {
            return false;
        }

        if (!exists(path)) {
            return false;
        }

        File directory = new File(path);
        File[] files = directory.listFiles();

        for (File fileForDeletion : files) {
            if (fileForDeletion.isFile()) {
                fileForDeletion.delete();
            } else {
                delete(fileForDeletion);
            }
        }

        return directory.delete();

    }

    /**
     * Recursivly delets a directory and all its files.  Returns {@code true} if successful.  Returns
     * {@code false} if path is null or does not exist.
     *
     * @param file
     * @return
     * @see #delete(java.lang.String)
     */
    public static synchronized boolean delete(File file) {
        return delete(file.getAbsolutePath());
    }





}
